#include "sysclientheartbeat.h"
#include "client-socket.h"
#include "cgproto.pb.h"

SysClientHeartbeat::SysClientHeartbeat()
{

}

void SysClientHeartbeat::_on_heartbeat_timer(uv_timer_t* handle)
{

    uv_stream_t* stream = reinterpret_cast<uv_stream_t*>(handle->data);
    ClientSocketProc *client = CAST_REF_TYPE_FROM_VOID(ClientSocketProc, stream->data);
    cgproto::HeartbeatRequest hbReq;
    client->msgSend(ProtoType::HEARTBEAT_REQUEST, static_cast<google::protobuf::Message&>(hbReq));
}

void SysClientHeartbeat::f__on_connect(CnsComponentPtr com, uv_connect_t* req, int status)
{
    uv_stream_t* stream;

    stream = req->handle;
    ClientSocketProc *client = CAST_REF_TYPE_FROM_VOID(ClientSocketProc, stream->data);

    uv_timer_init(client->getLoop(), &client->getHeartbeatMaker());
    client->getHeartbeatMaker().data = stream;
    uint64_t timeout = client->property("timeout").toULongLong();
    uv_timer_start(&client->getHeartbeatMaker(), _on_heartbeat_timer, 2000, timeout);
    _on_heartbeat_timer(&client->getHeartbeatMaker());
}

void SysClientHeartbeat::f__on_read(CnsComponentPtr com, cgproto::Message& msg)
{
    cgproto::HeartbeatResponse hbResp;
    ClientSocketProc *client = CAST_REF_TYPE_FROM_VOID(ClientSocketProc, com.data());
    if(client->getBaseProto().decode(msg.body().c_str(), static_cast<int>(msg.body().size()), hbResp))
    {
        CNSLOG_DEBUG(QString("receive server %1:%2 heartbeat response!").arg(client->getIp()).arg(client->getPort()));
    }
}
